package cn.zhku.thing.web.servlet;

import cn.itcast.commons.CommonUtils;
import cn.itcast.servlet.BaseServlet;
import cn.zhku.thing.domain.Thing;
import cn.zhku.thing.service.ThingService;
import cn.zhku.user.domain.User;
import net.sf.json.JSONSerializer;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class ThingServlet
 */
@WebServlet("/ThingServlet")
public class ThingServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	ThingService thingService = new ThingService();
	
	public String addThing(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			/*
			 * 1. 把表单数据封装到Book对象中
			 *   * 上传三步
			 */
			// 创建工厂
			DiskFileItemFactory factory = new DiskFileItemFactory(1500 * 1024, new File("F:/f/temp"));
			// 得到解析器
			
			ServletFileUpload sfu = new ServletFileUpload(factory);
			// 设置单个文件大小为15KB
			sfu.setFileSizeMax(2000 * 1024);
			// 使用解析器去解析request对象，得到List<FileItem>
			try {
				List<FileItem> fileItemList = sfu.parseRequest(request);
				/*
				 * * 把fileItemList中的数据封装到News对象中
				 *   > 把所有的普通表单字段数据先封装到Map中
				 *   > 再把map中的数据封装到News对象中
				 */
				Map<String,String> map = new HashMap<String,String>();
				for(FileItem fileItem : fileItemList) {
					if(fileItem.isFormField()) {
						map.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
					}
				}

				Thing thing = CommonUtils.toBean(map, Thing.class);
				System.out.println(thing);
				// 为Thing指定bid
				thing.setTid(CommonUtils.uuid());
				thing.setDate(new Date());
				//UserEntity user = (UserEntity) request.getSession().getAttribute("session_user");
				//thing.setUserId(user.getUserId());
				thing.setUserId(2);
				 
				/*
				 * 需要把Map中的cid封装到Category对象中，再把Category赋给Book
				 */
				
				/*
				 * 2. 保存上传的文件
				 *   * 保存的目录
				 *   * 保存的文件名称
				 */
				// 得到保存的目录
				String imgSavepath = this.getServletContext().getRealPath("/thing/img");
				// 得到文件名称：给原来文件名称添加uuid前缀！避免文件名冲突
				String imgName = fileItemList.get(2).getName();
				String imgFilename = CommonUtils.uuid() + imgName.substring(imgName.lastIndexOf("."));
				
				
				/*
				 * 校验文件的扩展名
				 */
				if(!imgFilename.toLowerCase().endsWith("jpg")) {
					request.setAttribute("msg", "您上传的图片不是JPG扩展名！");
					return "f:/thing/addThing.jsp" ;
				}
				
				
				// 使用目录和文件名称创建目标文件
				File imgFile = new File(imgSavepath, imgFilename);
				// 保存上传文件到目标文件位置
				fileItemList.get(2).write(imgFile);
				
				/*
				 * 3. 设置News对象的image，即把图片的路径设置给Book的image
				 */
				thing.setImage("/thing/img" + imgFilename);
				thing.setDate(new Date());
				
				
				/*
				 * 4. 使用NewsService完成保存
				 */
				thingService.add(thing);
				
				
				/*
				 * 校验图片的尺寸
				 */
				Image image = new ImageIcon(imgFile.getAbsolutePath()).getImage();
				if(image.getWidth(null) > 10000 || image.getHeight(null) > 10000) {
					imgFile.delete();//删除这个文件！
					request.setAttribute("msg", "您上传的图片尺寸超出了10000* 10000！");
					
					return "f:/thing/addThing.jsp" ;
				}
				
				
				/*
				 * 5. 返回到图书列表
				 */
				request.setAttribute("msg", "您上传成功！！");
				return "f:/thing/addThing.jsp" ;
			} catch (Exception e) { 
				if(e instanceof FileUploadBase.FileSizeLimitExceededException) {
					request.setAttribute("msg", "您上传的文件超出了1.4M");
					request.getRequestDispatcher("/thing/add.jsp")
							.forward(request, response);
				}
				throw new RuntimeException(e);
			}			
	}
	
	public void ThingJson(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");//
		response.setContentType("text/html;charset=utf-8");
		ArrayList<Thing> newsList = new ArrayList<Thing>();
		newsList = (ArrayList<Thing>) thingService.findAll();
		 String newsJson = JSONSerializer.toJSON(newsList).toString();
		
		 response.getWriter().print(newsJson); 
	}
	
	 public String query(HttpServletRequest request, HttpServletResponse response) 
				throws ServletException, IOException {
			request.setCharacterEncoding("utf-8");//
			response.setContentType("text/html;charset=utf-8"); 
			ArrayList<Thing> thingList = thingService.findAll();
			request.setAttribute("thingList", thingList);
			System.out.println(thingList);
			return "f:thing/list.jsp";	
	    }
		
	    public String edit(HttpServletRequest request, HttpServletResponse response) 
				throws ServletException, IOException {
			request.setCharacterEncoding("utf-8");//
			response.setContentType("text/html;charset=utf-8");
			
			Thing thing = CommonUtils.toBean(request.getParameterMap(), Thing.class);
			thingService.edit(thing);
			request.setAttribute("msg", "恭喜您，列表修改成功");
			this.query(request, response);
			return "f:thing/list.jsp";
	    }
	    
	    public String delete(HttpServletRequest request, HttpServletResponse response) 
				throws ServletException, IOException {
	    	request.setCharacterEncoding("utf-8");//
			response.setContentType("text/html;charset=utf-8");
			Thing thing = CommonUtils.toBean(request.getParameterMap(), Thing.class);
			thingService.delete(thing);
			request.setAttribute("msg", "恭喜您，列表修改成功");
			this.query(request, response);
			return "f:thing/list.jsp";
	    	
	    }

		
   

}
